package com.hyt.it.ogt.ks.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.common.apiInfor.DataType;
import com.hyt.common.apiInfor.ParamType;
import com.hyt.it.ogt.ks.config.KsBizRunTimeException;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.enums.ErrorTypeCode;
import com.hyt.it.ogt.ks.model.entity.CollectLog;
import com.hyt.it.ogt.ks.model.entity.MobileDeviceParam;
import com.hyt.it.ogt.ks.model.vo.monitor.response.CandidateExamStateVO;
import com.hyt.it.ogt.ks.model.vo.monitor.response.CandidateLoginVO;
import com.hyt.it.ogt.ks.model.vo.monitor.response.CandidateMonitorStartVO;
import com.hyt.it.ogt.ks.model.vo.monitor.response.CandidateValidPhoto;
import com.hyt.it.ogt.ks.model.vo.monitor.response.MonitorSignVO;
import com.hyt.it.ogt.ks.model.vo.monitor.response.WxLoginVO;
import com.hyt.it.ogt.ks.service.ICollectLogService;
import com.hyt.it.ogt.ks.service.IMobileService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信小程序
 *
 * @author 刘恒活
 * @since 2021/7/21 10:31
 */
@Api(tags = "11.微信小程序接口", value = "微信小程序接口")
@ApiSort(11)
@Slf4j
@RestController
@RequestMapping("/ks/wx/")
public class WxController {
    @Resource
    private IMobileService iMobileService;
    @Resource
    private ICollectLogService iCollectLogService;

    @ApiOperation(value = "11.1.1 微信登录", response = WxLoginVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jsCode", value = "jsCode", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(1)
    @GetMapping("wxLogin")
    public ApiResponse<WxLoginVO> wxLogin(@RequestParam String jsCode) {
        try {
            return ApiResponse.<WxLoginVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).build();
        } catch (KsBizRunTimeException e) {
            return ApiResponse.<WxLoginVO>builder().code(e.getCode()).build();
        } catch (Exception e) {
            log.error("微信登录wxLogin异常：{}", jsCode, e);
            return ApiResponse.<WxLoginVO>builder().code(BizStatusCode.WX_LOGIN_FAIL.getCode()).build();
        }
    }

    @ApiOperation(value = "11.1.2 业务登录", notes = "状态码：20000:成功，42050201：异常", response = CandidateLoginVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "准考证或身份证号", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "examCode", value = "考试ID", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "isScan", value = "是否扫描码登录1:是 0:否", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = false)
    })
    @ApiOperationSort(2)
    @GetMapping("login")
    public ApiResponse<CandidateLoginVO> login(@RequestParam String code, @RequestParam String examCode,
                                                @RequestParam(required = false,defaultValue = "0") Integer isScan) {
        try {
            return ApiResponse.<CandidateLoginVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(iMobileService.login(code, examCode,isScan)).build();
        } catch (Exception e) {
            log.error("移动端登陆异常:{}", e);
            return ApiResponse.<CandidateLoginVO>builder()
                    .code(BizStatusCode.VIDEO_MONITOR_MOBILE_LOGIN_FAIL_CODE.getCode())
                    .data(CandidateLoginVO.builder().status(6).msg("登录失败").build()).build();
        }
    }

    @ApiOperation(value = "11.1.3 获取签名", notes = "状态码：20000:成功，16323：考生不存在，42050101：异常",
            response = MonitorSignVO.class)
    @ApiOperationSort(3)
    @GetMapping("getSign")
    public ApiResponse<MonitorSignVO> getSign(@RequestParam String examId, @RequestParam String userId) {
        try {
            return ApiResponse.<MonitorSignVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(iMobileService.getSign(examId, userId)).build();
        } catch (Exception e) {
            log.error("获取签名报错:", e);
            iCollectLogService.save(CollectLog.builder().candidateId(userId).examId(examId)
                    .errorType(ErrorTypeCode.ERROR_MOBILE_GET_SIGN.getCode()).errMsg(e.toString()).build());
            return ApiResponse.<MonitorSignVO>builder()
                    .code(BizStatusCode.VIDEO_MONITOR_GET_SIGN_FAIL_CODE.getCode()).build();
        }
    }

    @ApiOperation(value = "11.1.4 获取考生照片列表", notes = "状态码：20000:成功，42050201：异常",
            response = CandidateValidPhoto.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(4)
    @GetMapping("getCandidateInfo")
    public ApiResponse<CandidateValidPhoto> getCandidateInfo(@RequestParam String userId) {
        try {
            return ApiResponse.<CandidateValidPhoto>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(iMobileService.getCandidateInfo(userId)).build();
        } catch (Exception e) {
            log.error("移动端登陆异常:{}", e);
            return ApiResponse.<CandidateValidPhoto>builder()
                    .code(BizStatusCode.VIDEO_MONITOR_MOBILE_LOGIN_FAIL_CODE.getCode()).build();
        }
    }

    @ApiOperation(value = "11.1.5 配对分析（人脸比对），返回值true表示验证通过，false表示验证不通过",
            notes = "状态码：20000:成功，18322：异常", response = Boolean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "imageUrlA", value = "第一张照片(后端返回的照片)", dataType = DataType.STRING,
                    paramType = ParamType.QUERY),
            @ApiImplicitParam(name = "imageUrlB", value = "第二张照片(后端返回的照片)", dataType = DataType.STRING,
                    paramType = ParamType.QUERY),
            @ApiImplicitParam(name = "imageUrlC", value = "第三张移动端拍照的照片(上传云存储后访问的绝对网络路径)",
                    dataType = DataType.STRING, paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(5)
    @PutMapping("faceMatch")
    public ApiResponse<Boolean> faceMatch(@RequestParam String examId, @RequestParam String userId, String imageUrlA,
                                           String imageUrlB, @RequestParam String imageUrlC) {
        try {
            return ApiResponse.<Boolean>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(iMobileService.faceMatchForWX(examId, userId, imageUrlA, imageUrlB, imageUrlC)).build();
        } catch (Exception e) {
            log.error("移动端配对分析异常:{}", e);
            return ApiResponse.<Boolean>builder().code(BizStatusCode.VIDEO_MONITOR_COMPARE_FACE_FAIL_CODE.getCode())
                    .build();
        }
    }

    @ApiOperation(value = "11.1.6 开始监控", notes = "状态码：20000:成功，42051501：异常", response = CandidateMonitorStartVO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "examId", value = "examId", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(6)
    @GetMapping("startMonitor")
    public ApiResponse<CandidateMonitorStartVO> startMonitor(@RequestParam String userId, @RequestParam String examId) {
        try {
            log.info("开始监控{}=={}", userId, examId);
            return ApiResponse.<CandidateMonitorStartVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(iMobileService.startMonitor(userId, examId)).build();
        } catch (Exception e) {
            log.error("移动端开始监控异常:{}", e);
            return ApiResponse.<CandidateMonitorStartVO>builder()
                    .code(BizStatusCode.VIDEO_MONITOR_START_MONITOR_ERROR_CODE.getCode()).build();
        }
    }

    @ApiOperation(value = "11.1.7 查看考生考试状态", notes = "状态码：20000:成功，18326：异常",
            response = CandidateExamStateVO.class)
    @ApiOperationSort(7)
    @GetMapping("getMonitorState")
    public ApiResponse<CandidateExamStateVO> getMonitorState(MobileDeviceParam param) {
        try {
            return ApiResponse.<CandidateExamStateVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(iMobileService.getMonitorState(param)).build();
        } catch (Exception e) {
            log.error("移动端开始监控异常:{}，{}", JSON.toJSONString(param), e);
            return ApiResponse.<CandidateExamStateVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(CandidateExamStateVO.builder().state(0).build()).build();
        }
    }
}
